<template>
  <div class="productAndPrice-container">
    <div class="top-operation-container">
      <el-row>
        <el-col :span="4">
          <el-button
            class="border-btn"
            size="mini"
            @click="create"
          >变更交易终端终端价</el-button>
        </el-col>
        <el-col :span="20">
          <div style="display: flex; justify-content: flex-end">
            <el-form
              :inline="true"
              :model="formData"
              label-position="right"
              size="small"
              class="filter-form-inline"
            >
              <el-row
                :gutter="40"
                style="margin-left: 0px; margin-right: 0px"
              >
                <el-form-item label="关键字搜索">
                  <el-input
                    v-model="formData.keyWord"
                    placeholder="请输入终端、渠道客户名称..."
                    @blur="refreshList"
                  >
                    <template #suffix>
                      <el-tooltip
                        class="box-item"
                        effect="dark"
                        content="请输入终端、渠道客户名称、关联产品价格编号"
                        placement="top"
                      >
                        <i class="iconfont icon-wenhao" />
                      </el-tooltip>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item>
                  <filter-popover
                    right="20px"
                    :form-list="formList"
                    @onConfirm="filterDataConfirm"
                    @onReset="filterReset"
                  />
                </el-form-item>
                <el-form-item style="margin-left: 20px;">
                  <table-cell-setting
                    :table-option="tableOption"
                    :checked="checkListData"
                    @checkList="checkList"
                  />
                </el-form-item>
              </el-row>
            </el-form>
          </div>
        </el-col>
      </el-row>

    </div>
    <div class="table-list">
      <el-table
        header-cell-class-name="table-header"
        :data="productPriceListData"
        border
        :cell-style="cellStyle"
        @row-click="rowClick"
      >

        <el-table-column
          v-if="checkListData.indexOf('terminalName') !== -1"
          prop="terminalName"
          label="终端名称"
          header-align="center"
          fixed="left"
          :min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            <div>
              <el-link
                type="primary"
                :underline="false"
              >{{ scope.row.terminalName }}</el-link>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('terminalArea') !== -1"
          prop="terminalArea"
          label="终端所在地区"
          header-align="center"
          :min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            <span>{{ scope.row.provinceName }} / {{ scope.row.cityName }} / {{ scope.row.areaName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('marketPrice') !== -1"
          :width="120"
          show-overflow-tooltip
          prop="productInfoDetail.marketPrice"
          label="市场价（元）"
          header-align="center"
          align="center"
        />
        <el-table-column
          v-if="checkListData.indexOf('terminalPrice') !== -1"
          :min-width="140"
          show-overflow-tooltip
          prop="terminalPrice"
          label="终端价（元）"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div style="line-height: 20px">
              <div>{{ scope.row.terminalPrice }}</div>
              <div
                v-if="scope.row.processDefinitionKey==='productPriceChange'&&scope.row.flowStatus==='DOING'"
                class="flow-status-color"
              >
                [终端价变更审核中]
              </div>
              <div
                v-if="scope.row.processDefinitionKey==='relationStandardChangeTerminalPrice'&&scope.row.flowStatus==='DOING'"
                class="flow-status-color"
              >
                [更换终端价审核中]
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('accessMode') !== -1"
          prop="accessMode"
          label="准入模式"
          :width="120"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div>{{ getLabel('access_mode', scope.row.accessMode) }}</div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('priceNumber') !== -1"
          prop="priceNumber"
          label="关联产品价格"
          :width="140"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div v-if="scope.row.productPriceStrategyDetail">
              {{ scope.row.productPriceStrategyDetail.priceNumber }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('sellMode') !== -1"
          prop="sellMode"
          label="营销模式"
          :width="140"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <span v-if="scope.row?.sellMode !== 'direct'">
              {{ scope.row?.agentAttribute === '1' ?'独家招商':'精细招商' }}
            </span>
            <span v-else> 终端直销</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('agentName') !== -1"
          prop="agentName"
          label="渠道客户名称"
          :min-width="140"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div v-if="scope.row.agentDetail">
              <el-link
                type="primary"
                :underline="false"
              >{{ scope.row.agentDetail.agentName }}</el-link>
            </div>
            <div v-else>无</div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('tradePrice') !== -1"
          prop="tradePrice"
          label="交易价（元）"
          :width="120"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div style="line-height:20px">
              <div>{{ scope.row.tradePrice }}</div>
              <div
                v-if="scope.row.processDefinitionKey==='agentProductChangePrice'&&scope.row.flowStatus==='DOING'||scope.row.agentPersonProductChangePrice==='agentPersonProductChangePrice'&&scope.row.flowStatus==='DOING'"
                class="flow-status-color"
              >
                [交易价变更审核中]
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('sellUnit') !== -1"
          prop="sellUnit"
          label="计价单位"
          :width="120"
          show-overflow-tooltip
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <div>
              <span>{{ getLabel('sell_unit', scope.row?.productInfoDetail.sellUnit) || '无' }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('createdAt') !== -1"
          prop="createdAt"
          label="创建时间"
          :width="140"
          header-align="center"
          align="center"
        >
          <template #default="scope">
            <span>{{ dateFormat('yyyy-mm-dd HH:MM', scope.row.createdAt) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="checkListData.indexOf('standardStatus') !== -1"
          prop="standardStatus"
          label="状态"
          :width="120"
          show-overflow-tooltip
          header-align="center"
          align="center"
          fixed="right"
        >
          <template #default="scope">
            <div>
              <span>{{ getLabel('standard_status', scope.row.standardStatus) }}</span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:page="formData.page"
        v-model:limit="formData.pageSize"
        style="display: flex; justify-content: flex-end"
        :total="total"
        @pagination="refreshList"
      />
    </div>
    <!-- 变更交易产品价格 -->
    <change-client-price
      ref="clientPriceRef"
      @onSuccess="refreshList"
    />
    <!--进货关系及价格详情-->
    <detail-drawer
      ref="detailDrawer"
      custom-title
      :size-width="1000"
    >
      <template #title>
        <span>进货关系及价格 - {{ rowData?.terminalName }}</span>
        <el-tag
          v-if="rowData?.standardStatus"
          size="small"
          style="margin-left: 5px"
          type="warning"
        >
          <span>{{ getLabel('standard_status', rowData?.standardStatus) }}</span>
        </el-tag>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <relationship
              ref="relationshipRef"
              :trading-product-id="rowData?.id"
            />
          </div>
          <div
            class="history-list"
            style="margin-top:20px;"
          >
            <item-title title="修改记录" />
            <operation-view
              :id="rowData?.devId"
              mode="dev"
            />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!--终端详情-->
    <detail-drawer
      ref="terminalDrawer"
      custom-title
    >
      <template #title>
        <span>终端信息 - {{ rowData?.terminalName }}</span>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <terminal-info :id="rowData?.terminalId" />
          </div>
        </div>
      </template>
    </detail-drawer>
    <!--渠道客户详情-->
    <detail-drawer
      ref="agentDrawer"
      custom-title
    >
      <template #title>
        <span>渠道客户 - {{ rowData?.agentName }}</span>
      </template>
      <template #contents>
        <div class="drawer-content">
          <div class="history-list">
            <agent-info :id="rowData?.agentId" />
          </div>
        </div>
      </template>
    </detail-drawer>
  </div>
</template>

<script>
import {defineAsyncComponent, getCurrentInstance, inject, onMounted, reactive, ref, toRefs,} from 'vue'
import {useRoute} from 'vue-router'
import {crmStore} from '@CRM/store'

export default {
  components: {
    changeClientPrice: defineAsyncComponent(() =>
      import('./modules/changeClientPrice.vue')
    ),
    relationship: defineAsyncComponent(() =>
      import(
        '@CRM/views/commonView/detailComponents/relationship/relationship.vue'
      )
    ),
    terminalInfo: defineAsyncComponent(() =>
      import('@CRM/views/commonView/detailComponents/terminal/terminalInfo.vue')
    ),
    agentInfo: defineAsyncComponent(() =>
      import('@CRM/views/commonView/detailComponents/agent/agentInfo.vue')
    ),
  },
  props: {
    detail: {
      type: Object,
      default: () => {},
    },
  },
  setup(props, context) {
    const route = useRoute()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    var productDetail = reactive(props.detail)
    var clientPriceRef = ref(null)
    var detailDrawer = ref(null)
    var terminalDrawer = ref(null)
    var agentDrawer = ref(null)
    var reactiveData = reactive({
      relationshipRef: null,
      total: 0,
      formData: {
        page: 1,
        pageSize: 20,
        productId: route.query.productId ? Number(route.query.productId) : 0,
        standardStatus: '',
        keyWord: '',
        accessMode: '',
        sellMode: '',
        terminalPriceMax: 0,
        terminalPriceMin: 0,
        tradePriceMax: 0,
        tradePriceMin: 0,
        provinceCode: '',
        cityCode: '',
        areaCode: '',
      },
      productPriceListData: [],
      formList: [
        {
          key: 'standardStatus',
          label: '交易状态',
          form_type: 'select',
          value: '',
          is_search: false,
          options:
            crmStore.getters['dictionary/getDictionary']['standard_status'],
        },
        {
          key: 'accessMode',
          label: '准入模式',
          form_type: 'select',
          value: '',
          is_search: false,
          options: crmStore.getters['dictionary/getDictionary']['access_mode'],
        },
        {
          key: 'sellMode',
          label: '营销模式',
          form_type: 'select',
          value: '',
          is_search: false,
          options: crmStore.getters['dictionary/getDictionary']['agent_type'],
        },
        {
          key: 'terminalPriceRange',
          label: '终端价范围',
          form_type: 'pricerange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'tradePriceRange',
          label: '交易价范围',
          form_type: 'pricerange',
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: 'area',
          label: '所在地区',
          form_type: 'cascader',
          value: [],
          is_search: false,
          multiple: false,
          options: [],
        },
      ],
      rowData: null,
    })
    var tableOption = reactive([
      { key: 'priceNumber', value: '关联产品价格' },
      { key: 'accessMode', value: '准入模式' },
      { key: 'terminalName', value: '终端名称' },
      { key: 'terminalArea', value: '终端所在地区' },
      { key: 'sellMode', value: '营销模式' },
      { key: 'terminalPrice', value: '终端价' },
      { key: 'agentName', value: '渠道客户名称' },
      { key: 'tradePrice', value: '交易价' },
      { key: 'createdAt', value: '创建时间' },
      { key: 'standardStatus', value: '状态' },
    ])
    var checkListData = ref([
      'priceNumber',
      'accessMode',
      'terminalName',
      'terminalArea',
      'sellMode',
      'sellUnit',
      'agentName',
      'tradePrice',
      'marketPrice',
      'terminalPrice',
      'standardStatus',
    ])
    const cellStyle = (row) => {
      if (row.column.label === '操作') return
      return 'cursor: pointer;'
    }
    const rowClick = (row, column, event) => {
      console.log(row, column.label, event)
      reactiveData.rowData = row
      if (column.label === '终端名称') {
        terminalDrawer.value.open()
      } else if (column.label === '渠道客户名称') {
        agentDrawer.value.open()
      } else {
        detailDrawer.value.open()
      }
    }
    const checkList = (checked) => {
      checkListData.value = checked
      console.log(checkListData)
    }
    // 判断操作按钮是否可用
    const isCreatePrice = () => {
      var obj = { disabled: false, msg: '' }
      if (productDetail.productStatus === '-1') {
        if (productDetail.flowStatus === 'DOING') {
          obj.disabled = true
          obj.msg = '产品审核中，暂不支持创建产品价格'
        }
      }
      if (productDetail.productStatus === '-2') {
        obj.disabled = true
        obj.msg = '产品已下架'
      }
      if (productDetail.productStatus === '1') {
        if (productDetail.flowStatus === 'DOING') {
          obj.disabled = true
          obj.msg = '产品审核中'
        }
      }
      return obj
    }
    // 变更交易终端价
    const create = () => {
      var isCreate = isCreatePrice()
      if (isCreate.disabled) {
        currentInstance.proxy.customMessage({
          type: 'error',
          message: isCreate.msg,
        })
        return
      }
      clientPriceRef.value.open(productDetail)
    }
    const getList = () => {
      api.product.PURCHASE_PRICE_LIST(reactiveData.formData).then((res) => {
        if (res.code === 0) {
          reactiveData.productPriceListData = res.data.list || []
          reactiveData.total = res.data.total || 0
        }
      })
    }
    const refreshList = () => {
      getList()
    }
    const filterReset = () => {
      reactiveData.formData = {
        productId: route.query.productId ? Number(route.query.productId) : 0,
        standardStatus: '',
        keyWord: '',
        accessMode: '',
        sellMode: '',
        terminalPriceMax: 0,
        terminalPriceMin: 0,
        tradePriceMax: 0,
        tradePriceMin: 0,
        area: [],
        provinceCode: '',
        cityCode: '',
        areaCode: '',
      }
      getList()
    }
    const filterDataConfirm = (formdata) => {
      reactiveData.formData.standardStatus = formdata.standardStatus
      reactiveData.formData.accessMode = formdata.accessMode
      reactiveData.formData.sellMode = formdata.sellMode
      reactiveData.formData.terminalPriceMin =
        formdata.terminalPriceRange && formdata.terminalPriceRange.length
          ? formdata.terminalPriceRange[0]
          : 0
      reactiveData.formData.terminalPriceMax =
        formdata.terminalPriceRange && formdata.terminalPriceRange.length
          ? formdata.terminalPriceRange[1]
          : 0
      reactiveData.formData.tradePriceMin =
        formdata.tradePriceRange && formdata.tradePriceRange.length
          ? formdata.tradePriceRange[0]
          : 0
      reactiveData.formData.tradePriceMax =
        formdata.tradePriceRange && formdata.tradePriceRange.length
          ? formdata.tradePriceRange[1]
          : 0
      // 所在地区
      if (formdata.area && formdata.area.length) {
        reactiveData.formData.provinceCode = formdata.area[0]
        reactiveData.formData.cityCode = formdata.area[1]
        reactiveData.formData.areaCode = formdata.area[2]
      } else {
        reactiveData.formData.provinceCode = ''
        reactiveData.formData.cityCode = ''
        reactiveData.formData.areaCode = ''
      }

      getList()
    }

    onMounted(() => {
      if (reactiveData.formData.productId) {
        getList()
      }
    })

    return {
      clientPriceRef,
      detailDrawer,
      terminalDrawer,
      agentDrawer,
      cellStyle,
      rowClick,
      productDetail,
      ...toRefs(reactiveData),
      tableOption,
      checkListData,
      checkList,
      create,
      refreshList,
      filterReset,
      filterDataConfirm,
    }
  },
}
</script>

  <style lang="scss" scoped>
@import "@CRM/assets/scss/views/product/productAndPrice.scss";
</style>

